package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.config.ExtensionConfig;
import com.example.remote.InventoryService;
import com.example.demo.User;
import com.example.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@RestController
@RequestMapping("/order")
@Slf4j
@RefreshScope  // 可以刷新nacos配置中心的配置
public class OrderController {
    //@Qualifier("inventory-nacos")
    //@Autowired
    //private InventoryService inventoryService;
    @Value("${student.name}")
    private String username;
    @Autowired
    private ExtensionConfig extensionConfig;

    @Autowired
    private OrderService orderService;


    @GetMapping("/createOrder.do")
    @SentinelResource(value = "createOrder",fallback ="createOrderFallback",blockHandler = "createOrderBlockHandler")
    public String createOrder(){
        //String username = configurableApplicationContext.getEnvironment().getProperty("user.name1");
        System.out.println("create order success..."+username +";extension:" +extensionConfig.getName() +";age="+extensionConfig.getAge());
        int a = new Random().nextInt(2)+1;
        orderService.placeOrder("1223", "product-" + a,a);
        //int a = 1/0;
        System.out.println("inventoryService.decreInventory result");
        return "success";
    }

    public String createOrderBlockHandler(BlockException e){
        log.info("createOrderBlockHandler....");
        e.printStackTrace();

        return "流控";
    }

    public String createOrderFallback(Throwable e){
        log.info("fallbackClass....");
        e.printStackTrace();
        return "异常";
    }

    @PostMapping("/getUser.do")
    public User getUser(@RequestBody User user){
        user.setAge(25);
        user.setName("小张脏");
        return user;
    }
}
